var companyId = "";
var departmentId = "";
var jobId = "";
var jobScoreId = "";

layui.config({
    base: basePath,
    version: skyeyeVersion
}).extend({
    window: 'js/winui.window'
}).define(['window', 'table', 'jquery', 'winui', 'dtree', 'laydate'], function (exports) {
    winui.renderColor();
    layui.use(['form'], function (form) {
        var index = parent.layer.getFrameIndex(window.name);
        var $ = layui.$,
            laydate = layui.laydate,
            dtree = layui.dtree;
        let userMation = {};

        // 获取URL参数中的id
        const userId = GetUrlParam("id") || '';

        // 初始化日期选择器
        laydate.render({
            elem: '#workTime',
            type: 'date',
            format: 'yyyy-MM-dd',
            trigger: 'click',
            done: function (value, date) {
                if (!isNull(value)) {
                    // 获取入职时间
                    var entryTimeStr = $("#entryTime").val();
                    if (!isNull(entryTimeStr)) {
                        var workDate = new Date(value);
                        var entryDate = new Date(entryTimeStr);

                        // 检查入职时间不能早于参加工作时间
                        if (entryDate < workDate) {
                            $("#workTime").val('');
                            winui.window.msg('参加工作时间不能晚于入职时间', { icon: 2, time: 2000 });
                        }
                    }
                }
            }
        });

        laydate.render({
            elem: '#entryTime',
            type: 'date',
            format: 'yyyy-MM-dd',
            trigger: 'click',
            done: function (value, date) {
                if (!isNull(value)) {
                    // 获取参加工作时间
                    var workTimeStr = $("#workTime").val();
                    if (!isNull(workTimeStr)) {
                        var entryDate = new Date(value);
                        var workDate = new Date(workTimeStr);

                        // 检查入职时间不能早于参加工作时间
                        if (entryDate < workDate) {
                            $("#entryTime").val('');
                            winui.window.msg('入职时间不能早于参加工作时间', { icon: 2, time: 2000 });
                        }
                    }
                }
            }
        });

        laydate.render({
            elem: '#trialTime',
            type: 'date',
            format: 'yyyy-MM-dd',
            trigger: 'click'
        });

        // 监听状态选择，显示/隐藏试用期
        form.on('select(stateFilter)', function (data) {
            if (data.value == 4) { // 试用期状态
                $("#trialTimeBox").show();
            } else {
                $("#trialTimeBox").hide();
            }
        });

        // 查询用户数据
        showGrid({
            id: "showForm",
            url: reqBasePath + "queryTenantUserById",
            params: { id: userId },
            pagination: false,
            method: "GET",
            template: $("#beanTemplate").html(),
            ajaxSendLoadBefore: function (hdb) {
                hdb.registerHelper("equal", function (v1, v2, options) {
                    if (v1 == v2) {
                        return options.fn(this);
                    } else {
                        return options.inverse(this);
                    }
                });

                // 为Handlebars注册if-equal助手函数
                hdb.registerHelper('if', function (conditional, options) {
                    if (conditional) {
                        return options.fn(this);
                    } else {
                        return options.inverse(this);
                    }
                });
            },
            ajaxSendAfter: function (json) {
                userMation = json.bean;

                // 加载学历和政治面貌数据字典
                sysDictDataUtil.showDictDataListByDictTypeCode(sysDictData["employeeEducation"]["key"], 'select', 'highestEducation', userMation.highestEducation, form, function () {
                    form.render('select'); // 确保select重新渲染
                    // 加载下一个数据字典
                    sysDictDataUtil.showDictDataListByDictTypeCode(sysDictData["employeesPoliticalOutlook"]["key"], 'select', 'politicId', userMation.politicId, form, function () {
                        form.render('select');
                    });
                });

                // 初始化公司树
                dtree.render({
                    elem: "#companyTree",
                    url: reqBasePath + 'queryCompanyMationListTree',
                    dataStyle: 'layuiStyle',
                    done: function (data) {
                        if ($("#companyTree li").length > 0) {
                            for (var i = 0; i < $("#companyTree li").length; i++) {
                                if ($("#companyTree li").eq(i).attr("data-id") == json.bean.companyId) {
                                    $("#companyTree li").eq(i).children('div').click();
                                    return;
                                }
                            }
                        }
                    }
                });


                // 公司树点击事件
                dtree.on("node('companyTree')", function (param) {
                    companyId = param.nodeId;
                    // 初始化部门
                    dtree.render({
                        elem: "#departmentTree",
                        url: reqBasePath + 'companydepartment006?companyId=' + companyId,
                        dataStyle: 'layuiStyle',
                        done: function (data) {
                            departmentId = "";
                            if ($("#departmentTree li").length > 0) {
                                for (var i = 0; i < $("#departmentTree li").length; i++) {
                                    if ($("#departmentTree li").eq(i).attr("data-id") == json.bean.departmentId) {
                                        $("#departmentTree li").eq(i).children('div').click();
                                        return;
                                    }
                                }
                            } else {
                                jobId = "";
                                //初始化职位
                                dtree.render({
                                    elem: "#jobTree",
                                    url: reqBasePath + 'companyjob006?departmentId=0',
                                    dataStyle: 'layuiStyle',
                                    done: function (json) {
                                    }
                                });
                            }
                        }
                    });
                });

                // 部门树点击事件
                dtree.on("node('departmentTree')", function (param) {
                    departmentId = param.nodeId;
                    //初始化职位
                    dtree.render({
                        elem: "#jobTree",
                        url: reqBasePath + 'companyjob006?departmentId=' + departmentId,
                        dataStyle: 'layuiStyle',
                        done: function (data) {
                            jobId = "";
                            if ($("#jobTree li").length > 0) {
                                for (var i = 0; i < $("#jobTree li").length; i++) {
                                    if (json.bean && $("#jobTree li").eq(i).attr("data-id") == json.bean.jobId) {
                                        $("#jobTree li").eq(i).children('div').click();
                                        return;
                                    }
                                }
                            }
                        }
                    });
                });

                // 职位树点击事件
                dtree.on("node('jobTree')", function (param) {
                    jobId = param.nodeId;
                    // 初始化职位定级
                    dtree.render({
                        elem: "#jobScoreTree",
                        url: reqBasePath + 'companyjobscore008?jobId=' + jobId,
                        dataStyle: 'layuiStyle',
                        method: 'GET',
                        done: function (data) {
                            jobScoreId = "";
                            if ($("#jobScoreTree li").length > 0) {
                                for (var i = 0; i < $("#jobScoreTree li").length; i++) {
                                    if ($("#jobScoreTree li").eq(i).attr("data-id") == json.bean.jobScoreId) {
                                        $("#jobScoreTree li").eq(i).children('div').click();
                                        return;
                                    }
                                }
                            }
                        }
                    });
                });

                // 职位定级树点击事件
                dtree.on("node('jobScoreTree')", function (param) {
                    jobScoreId = param.nodeId;
                });


                // 加载角色列表
                loadRoleList(userMation.staffId, userMation.isAdmin);

                // 加载考勤时间段
                loadCheckTimeList(json.bean.timeList || []);

                matchingLanguage();
                form.render();

                // 监听表单提交
                form.on('submit(formEditUser)', function (data) {
                    if (winui.verifyForm(data.elem)) {

                        // 验证职位信息
                        if (isNull(companyId)) {
                            winui.window.msg('请选择所属公司', { icon: 2, time: 2000 });
                            return false;
                        }
                        if (isNull(departmentId)) {
                            winui.window.msg('请选择所属部门', { icon: 2, time: 2000 });
                            return false;
                        }
                        if (isNull(jobId)) {
                            winui.window.msg('请选择职位信息', { icon: 2, time: 2000 });
                            return false;
                        }

                        // 验证试用期
                        var state = $("#state").val();
                        if (state == 4 && isNull($("#trialTime").val())) {
                            winui.window.msg('请选择试用期到期时间', { icon: 2, time: 2000 });
                            return false;
                        }

                        // 获取是否管理员
                        var isAdmin = $("#isAdmin").val();

                        // 验证角色 - 仅当不是管理员时才验证
                        var roleIdList = [];
                        $.each($('#roleList input[type=checkbox]:checked'), function () {
                            roleIdList.push($(this).val());
                        });
                        if (isAdmin != 1 && roleIdList.length == 0) {
                            winui.window.msg('请选择至少一个角色', { icon: 2, time: 2000 });
                            return false;
                        }

                        // 验证考勤段
                        var timeIds = [];
                        $.each($('#checkTimeBox input:checkbox:checked'), function () {
                            timeIds.push($(this).attr("rowId"));
                        });
                        if (timeIds.length == 0) {
                            winui.window.msg('请选择考勤段', { icon: 2, time: 2000 });
                            return false;
                        }

                        // 构建提交参数
                        var params = {
                            id: $("#id").val() || userId || '',
                            staffId: $("#staffId").val() || '',
                            workTime: $("#workTime").val(),
                            entryTime: $("#entryTime").val(),
                            trialTime: $("#trialTime").val(),
                            state: $("#state").val(),
                            nativePlace: $("#nativePlace").val(),
                            maritalStatus: $("#maritalStatus").val(),
                            politicId: $("#politicId").val(),
                            highestEducation: $("#highestEducation").val(),
                            roleId: roleIdList.join(','),
                            tenantId: getTenantId(),
                            companyId: companyId,
                            departmentId: departmentId,
                            jobId: jobId,
                            jobScoreId: jobScoreId,
                            isAdmin: $("#isAdmin").val(),
                            timeIdList: JSON.stringify(timeIds)
                        };

                        // 发送保存请求
                        AjaxPostUtil.request({
                            url: reqBasePath + "editTenantUserById",
                            params: params,
                            type: 'json',
                            method: 'POST',
                            callback: function (json) {
                                parent.layer.close(index);
                                parent.refreshCode = '0';
                            }
                        });
                    }
                    return false;
                });

            }
        });

        // 加载角色列表
        function loadRoleList(staffId, isAdmin) {
            if (isAdmin == 1) {
                // 管理员不加载角色列表，并隐藏相关区域
                $('#roleInfoSection').hide();
                $('#roleListSection').hide();
                return;
            } else {
                $('#roleInfoSection').show();
                $('#roleListSection').show();
            }
            showGrid({
                id: "roleList",
                url: reqBasePath + "sys019",
                params: { id: staffId || '' },
                pagination: false,
                template: getFileContent('tpl/sysEveUser/roleList.tpl'),
                ajaxSendLoadBefore: function (hdb) {
                },
                ajaxSendAfter: function (json) {
                    form.render('checkbox');
                }
            });
        }

        // 加载考勤时间段
        function loadCheckTimeList(selectedTimeList) {
            showGrid({
                id: "checkTimeBox",
                url: sysMainMation.checkworkBasePath + "queryEnableCheckWorkTimeList",
                params: {},
                method: 'GET',
                pagination: false,
                template: $("#checkTimeStrTemplate").html(),
                ajaxSendLoadBefore: function (hdb) {
                },
                ajaxSendAfter: function (data) {
                    // 设置已选择的考勤段
                    if (selectedTimeList && selectedTimeList.length > 0) {
                        for (var i = 0; i < selectedTimeList.length; i++) {
                            $('input:checkbox[rowId="' + selectedTimeList[i].timeId + '"]').attr("checked", true);
                        }
                    }
                    form.render('checkbox');
                }
            });
        }

        // 取消按钮
        $("body").on("click", "#cancle", function () {
            parent.layer.close(index);
        });

        // 页面初始化时调用
        loadRoleList($('#staffId').val(), $('#isAdmin').val());
    });
});
